<?php

	/**
	 * Workspace@ Engine application comment!
	 * 
	 * LICENSE
	 * This application is licensed under New BSD license.
	 * Please read complete LICENSE.txt inside of root folder for more details.
	 * 
	 * We wish you good building :) 
	 * 
	 * @category   Application
	 * @package    Bootstrap
	 * @author     Nevio Vesic <nevio@workspaceat.com>
	 * @copyright  2008-2009 Workspace@ group in association with Design strategist
	 */

	class Engine_Plugins_Pagegroup extends Engine_Application_Abstract
	{
		
		protected $db          = null;

		/**
		 * Group id temporairly id ( used for ajax when adding group or modifying group )
		 * 
		 * @var int[group id]
		 */
		private static $groupid = null;
		
		/**
		 * Counter for building directories
		 * Don't fuk with it :D
		 */
		protected $counter = null;
		
		/**
		 * Array data a.k.a parent groups.
		 * Used when building directories for parent group.
		 * We need to somehow findout base directory....
		 */
		protected $arrdata = null;
		
		/**
		 * Group real status. When group is building it will say inprogress.
		 * Later after group has been finished, than he will read this value
		 * and publish it or disable it.
		 * Start value is added at addGroup method
		 * 
		 * @var int[group id]
		 */
		private static $status  = null;
		
		function __construct()
		{
			
			$this->db = $this->databaseInstance();
		
		}
		
		public function addAboutGroup ( Zend_Config $data )
		{
			if (! $data -> name )
			{
				return array (
					"status" => "false",
					"input"  => "name",
					"message" => "Group name must be specified!"
				);
				die();
			}
			
			if (! $data -> status )
			{
				return array (
					"status" => "false",
					"input"  => "status",
					"message" => "Status must be specified!"
				);
				die();
			}
			
			if (! $data -> type )
			{
				return array (
					"status" => "false",
					"input"  => "type",
					"message" => "Group type must be specified!"
				);
				die();
			}
			
			if (! $data -> description || strlen ( $data -> description ) < 10 )
			{
				return array (
					"status" => "false",
					"input"  => "description",
					"message" => "Description must be specified and grater than 10 chars!"
				);
				die();
			}
			
			# lets see if current group exists - standalone
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			$unixname = strtolower( $this->replaceChars( $data -> name ) );
			
			$preresult = $this->db->fetchRow ("SELECT id FROM page_groups WHERE unixname='{$unixname}' AND type='standalone'" );
			
			if($preresult)
			{
				return array (
					"status" => "false",
					"input"  => "name",
					"message" => "Current group already exists!"
				);
				die();
			}
			
			$preresult2 = $this->db->fetchRow ("SELECT id FROM page_groups WHERE unixname='{$unixname}' AND type='parent' AND parentof='{$data->parents}'" );
			
			if($preresult2)
			{
						if($preresult2)
			{
				return array (
					"status" => "false",
					"input"  => "name",
					"message" => "Current group already exists!"
				);
				die();
			}
			}
			
			# Ok lets add things into database
			
			if ( $data -> parents )
			{
				
				$parent = $data -> parents;
				
			}else{
				
				$parent = "0";
			
			}
			
			$result = $this->db->query("INSERT INTO page_groups (garbaged, name, unixname, type, parentof, description, status, progressof, lastchange, createdat)
			VALUES('false', '{$data->name}', '{$unixname}', '{$data->type}', '{$parent}', '{$data->description}', '{$data->status}', '2', NOW(), NOW())");
			
			if (! $result )
			{
				return array (
					"status" => "false",
					"input"  => "",
					"task"   => "2",
					"message" => "Sql error. Please try later or contact community!"
				);
				die();
			}
			
			# ok lets go now to build exact location of directory.
			if ( $data -> type == 'standalone')
			{
				if ( self::$plugins->builder->createFrontendDir( strtolower ( $unixname ) ) )
				{
					return array (
						"status" => "true",
						"input"  => "",
						"task"   => "finish",
						"message" => "Group has been successfuly created!"
					);
					die();	
				}else{
					return array (
						"status" => "false",
						"input"  => "",
						"task"   => "2",
						"message" => "Creating dir error. Please try later or contact community!"
					);
					die();
				}
			}
			elseif ( $data->type == 'parent' )
			{
				# let's trick counter :D
				if ( $this->counter )
				{
					$this->counter = null;
				}
				$this->counter = $data->parents;
				
				$fukit = null;
				
				while($this->counter !== 0 ){
					
					# do some nasty hack for while loop... I hate infinte loops 
					if (! $fukit )
					{
						$resultdir = $this->db->fetchRow ( "SELECT id, unixname, parentof 
						FROM page_groups WHERE id='{$data->parents}' AND status='true'" );
						
						if ( $fukit )
						{
							$fukit = null;
						}
						$fukit = $resultdir->parentof;
					}
					else{
						$resultdir = $this->db->fetchRow ( "SELECT id, unixname, parentof 
						FROM page_groups WHERE id='{$fukit}' AND status='true'" );
						if ( $fukit )
						{
							$fukit = null;
						}
						$fukit = $resultdir->parentof;
					}
					
					$this->arrdata[] = strtolower( $resultdir->unixname );
					
					if ( $this->counter )
					{
						$this->counter = null;
					}
					$this->counter = $resultdir->parentof;
					
				}
				
				# used for adding paths so that we know last position
				$rpath = null;
				
				# lets reverse array for now
				$reversed = array_reverse( $this->arrdata );
				
				# ok lets now check if directories of array exists, if not create one.
				foreach ( $reversed as $path )
				{
					$rpath .= $path . DIRECTORY_SEPARATOR;
					self::$plugins->builder->createFrontendDir( strtolower ( $rpath ) );
				}
				
				$rpath2 = $rpath . strtolower($unixname) . DIRECTORY_SEPARATOR;
				self::$plugins->builder->createLanguageDir($rpath2);
				
				# ok lets finish it...
				
				if( self::$plugins->builder->createFrontendDir( strtolower ( $rpath2 ) ) )
				{
					return array (
						"status" => "true",
						"input"  => "",
						"task"   => "finish",
						"message" => "Group has been successfuly created!"
					);
					die();
				}
				else
				{
					return array (
						"status" => "false",
						"input"  => "",
						"task"   => "2",
						"message" => "Creating dir error. Please try later or contact community!"
					);
					die();
				}
				
			}
		}
		
		public function manageAboutGroup(Zend_Config $data )
		{
			if (! $data -> name )
			{
				return array (
					"status" => "false",
					"input"  => "name",
					"message" => "Group name must be specified!"
				);
				die();
			}
			
			if (! $data -> status )
			{
				return array (
					"status" => "false",
					"input"  => "status",
					"message" => "Status must be specified!"
				);
				die();
			}
			
			if (! $data -> type )
			{
				return array (
					"status" => "false",
					"input"  => "type",
					"message" => "Group type must be specified!"
				);
				die();
			}
			
			if (! $data -> description || strlen ( $data -> description ) < 10 )
			{
				return array (
					"status" => "false",
					"input"  => "description",
					"message" => "Description must be specified and grater than 10 chars!"
				);
				die();
			}
			
			# lets see if current group exists - standalone
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			$unixname = strtolower( $this->replaceChars( $data -> name ) );
		}
		
		/**
		 * Get current active groups from database
		 *
		 * @return Object[Zend_Db]
		 */
		public function getActiveGroups()
		{
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);

			$results = $this->db->fetchAll( "SELECT id, name, unixname, type, parentof FROM page_groups WHERE status='true' 
			AND garbaged='false' ORDER BY id DESC" );
			
			return $results;
		}
		
		/**
		 * Get current group from database by specified id
		 *
		 * @param  Zend_Config      $data
		 * @return Object[Zend_Db]
		 */
		public function getGroupById( $id )
		{
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);

			$results = $this->db->fetchRow( "SELECT * FROM page_groups 
			WHERE status='true' AND garbaged='false' AND id='{$id}'" );
			
			return $results;
		}
		
		/**
		 * This method will garbage group recived over params and all pages under it!
		 * 
		 * @param  Zend_Config   $data
		 * @return array()
		 */
		public function garbageGroup( Zend_Config $data )
		{
			
			# lets find group
			$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
			$group = $this->db->fetchRow("SELECT id FROM page_groups WHERE id='{$data->id}' AND unixname='{$data->name}'" );
			
			# lets garbage group
			$ggroup = $this->db->query( "UPDATE page_groups 
											SET
												garbaged = 'true',
												status   = 'false'
										WHERE id ='{$data->id}'" );
			
			$ggroup2 = $this->db->query( "UPDATE pages 
											SET
												garbaged = 'true',
												status   = 'false'
										WHERE id ='{$data->id}'" );
										
			if ( $ggroup && $ggroup2 )
			{
		
				return array (
					"status" => "true",
					"message" => "Selected group has been succesfully garbaged! Please wait..."
				);
				die();
			}
			else
			{
				return array (
					"status" => "false",
					"message" => "Sql error. Please try later or contact community!"
				);
				die();
			}
		}
		
		private function setAddGroupId( $id )
		{
			if ( self::$groupid )
			{
				self::$groupid = null;
			}
			
			self::$groupid = $id;
		}
		
		private function getAddGroupId( )
		{
			return self::$groupid;
		}
		
		
		/**
		 * Stupid function for replacing illegal characters with "" and white spaces with -
		 *
		 * @param  string $str
		 * @return string
		 */
		private function replaceChars($str)
		{
			$a = str_replace("`", "", $str );
			$b = str_replace("~", "", $a   );
			$c = str_replace("`", "", $b   );
			$d = str_replace("!", "", $c   );
			$e = str_replace("@", "", $d   );
			$f = str_replace("#", "", $e   );
			$g = str_replace("$", "", $f   );
			$h = str_replace("%", "", $g   );
			$i = str_replace("^", "", $h   );
			$j = str_replace("&", "", $i   );
			$k = str_replace("*", "", $j   );
			$l = str_replace("(", "", $k   );
			$m = str_replace(")", "", $l   );
			$n = str_replace("}", "", $m   );
			$o = str_replace("{", "", $n   );
			$p = str_replace("[", "", $o   );
			$r = str_replace("]", "", $p   );
			$s = str_replace(":", "", $r   );
			$t = str_replace("\\", "", $s   );
			$u = str_replace("/", "", $t   );
			$v = str_replace("'", "", $u   );
			$x = str_replace("\"", "", $v   );
			$y = str_replace("|", "", $x   );
			$z = str_replace("<", "", $y   );
			$a1 = str_replace(">", "", $z   );
			$a2 = str_replace(";", "", $a1   );
			$a3 = str_replace(" ", "-", $a2   );
			$a4 = str_replace("=", "", $a3   );
			$a5 = str_replace(",", "", $a4   );
			$a6 = str_replace(".", "_", $a5   );
			return $a6;
		}		
		
	}